package com.jp.knowledge.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import com.jp.knowledge.R;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.export.external.interfaces.WebResourceResponse;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.util.List;

/**
 * Created by 528787067@qq.com on 2017/4/12.
 */

public class JpNewsDetailWebView extends JpWebView {

	private String url;
	private String html;

	private static final String LOACL_HTML_JS_TEMPLATE_PATH = "file:///android_asset/htmlTemplate.js";
	private static final String LOCAL_HTML_TEMPLE_FILE_NAME = "htmlTemplate.html";
	private static final String LOCAL_IMG_TEMPLE_FILE_NAME = "htmlDetailTemplate.html";

	public JpNewsDetailWebView(Context context) {
		super(context);
	}

	public JpNewsDetailWebView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public JpNewsDetailWebView(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
	}

	@Override
	protected void init(Context context) {
		super.init(context);
		getWebSettings().setSupportZoom(true);
		webView.setOnTouchListener(new OnTouchListener() {
			private float doneY;

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (getLoadingAnimationView().getVisibility() != View.VISIBLE)
					return false;
				if (event.getAction() == MotionEvent.ACTION_DOWN)
					doneY = event.getY();
				else if (event.getAction() == MotionEvent.ACTION_MOVE
						&& Math.abs(event.getY() - doneY) > 50)
					getLoadingAnimationView().setVisibility(View.GONE);
				return false;
			}
		});
	}

	@Override
	public boolean loadUrl(String url) {
		this.url = url;
		return super.loadUrl(url);
	}

	@Override
	public boolean loadHtml(String html) {
		if (html == null)
			return false;
		loadDetailHtml(html, null, null, null, null);
		return true;
	}

	public void loadDetailHtml(final String html, final String tag, final String title, final String url, final String content) {
		if (html == null)
			return;
		this.html = html;
		String webHtml = getHtmlTemple(LOCAL_HTML_TEMPLE_FILE_NAME);
		webHtml = webHtml.replace("$[htmlContent]", html);
		webView.setWebViewClient(new WebViewClient(){
			@Override
			public void onPageStarted(WebView webView, String s, Bitmap bitmap) {
				webViewClient.onPageStarted(webView, s, bitmap);
			}
			@Override
			public void onReceivedError(WebView webView, int i, String s, String s1) {
				webViewClient.onReceivedError(webView, i, s, s1);
			}
			@Override
			public void onReceivedHttpError(WebView webView, WebResourceRequest webResourceRequest, WebResourceResponse webResourceResponse) {
				webViewClient.onReceivedHttpError(webView, webResourceRequest, webResourceResponse);
			}
			@Override
			public void onPageFinished(final WebView webView, final String s) {
				loadJavaScript(String.format("setCopyright('%s', '%s', '%s', '%s')",
						tag == null ? "" : tag,
						title == null ? "" : title,
						url == null ? "" : url,
						content == null ? "" : content));
				webViewClient.onPageFinished(webView, s);
//				JpNewsDetailWebView.this.webView.setWebViewClient(webViewClient);
			}
		});
		webView.loadDataWithBaseURL(LOACL_HTML_JS_TEMPLATE_PATH, webHtml, "text/html", "utf-8", null);
	}

	public void loadSvgImgs(List<String> imgs){
		if(imgs == null || imgs.size() == 0)
			return;
		String webHtml = getHtmlTemple(LOCAL_IMG_TEMPLE_FILE_NAME);
		String webImgHtml = "";
		for(String imgPath : imgs){
			webImgHtml += "<div class=\"ImageView\">" +
					"<img class=\"\" src=\"" + imgPath + "\" style=\"opacity: 1; width: 100%; height: auto;\">" +
					"</div>";
		}
		webHtml = webHtml.replace("#html#", webImgHtml);
		webView.loadDataWithBaseURL(null, webHtml, "text/html", "utf-8", null);
	}

	@Override
	public void reload() {
		webView.clearView();
		if ("data:text/html;charset=utf-8;base64,".equals(webView.getUrl())
				|| "about:blank".equals(webView.getUrl())) {
			loadHtml(html);
		} else {
			loadUrl(url);
		}
	}

	@Override
	protected void onPageFinished(WebView webView, String url) {
		super.onPageFinished(webView, url);
//        String imgCallbackJs = "" +
//                "(function(){                                                 " +
//                "   var imgDoc = document.getElementsByTagName(\"img\");      " +
//                "   var size = imgDoc.length;                                 " +
//                "   var ImgUrl = [];                                          " +
//                "   for (var i = 0; i < size; i++) {                          " +
//                "       var img = imgDoc[i];                                  " +
//                "       ImgUrl.push(img.getAttribute(\"src\"));               " +
//                "       img.setAttribute(\"index\", i);                       " +
//                "       img.onclick = function() {                            " +
//                "           var index = this.getAttribute(\"index\");         " +
//                "           var clickData = {                                 " +
//                "               \"key\": \"click\",                           " +
//                "               \"param\": index                              " +
//                "           };                                                " +
//                "           Android.jsCallback(JSON.stringify(clickData));    " +
//                "       }                                                     " +
//                "   }                                                         " +
//                "   var data = {                                              " +
//                "       \"key\": \"data\",                                    " +
//                "       \"param\": ImgUrl                                     " +
//                "   };                                                        " +
//                "   Android.jsCallback(JSON.stringify(data));                 " +
//                "})()";
//        loadJavaScript(imgCallbackJs);
	}

	private boolean strIsEmpty(String str) {
		if (str == null || str.trim().length() == 0)
			return true;
		return false;
	}
}
